package com.hh.fudan.project_management;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.hh.fudan.project_management.adapters.SearchAdapter;
import com.hh.fudan.project_management.basic.Global;
import com.hh.fudan.project_management.basic.TextUtil;
import com.hh.fudan.project_management.bean.ListItemResult;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SearchActivity extends Activity {
	Toast toast;
	int cityIndex = 0;
	private Spinner citySpinner;
	private String[] cities;
	private ArrayAdapter<String> cityAdapter;// cityAdapter
	private Button btn;// search button
	private Button orderBtn;// order button
	int order = 0;// 0.按结束时间从先到后排序 1.按价格从低到高排序 2.按折扣从低到高排序 3.按销量从高到低排序 4.按团购网站排序
	private ListView lv;
	private List<ListItemResult> searchResultList = new ArrayList<ListItemResult>();
	private List<String> images = new ArrayList<String>();
	private TextView viewGone;
	private TextView viewLoading;
	private TextView viewMore;
	private SearchAdapter searchAdapter;
	private int curPage = 0;
	private int lastVisibleItem = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_layout);
		viewGone = (TextView) findViewById(R.id.view_gone);
		viewGone.setVisibility(View.GONE);
		viewLoading = (TextView) findViewById(R.id.view_loading);
		viewLoading.setVisibility(View.GONE);
		viewMore = (TextView) findViewById(R.id.view_more);
		viewMore.setVisibility(View.GONE);

		lv = (ListView) findViewById(R.id.list_view);

		toast = Toast.makeText(this, null, Toast.LENGTH_SHORT);
		citySpinner = (Spinner) findViewById(R.id.spinner1);

		cities = getResources().getStringArray(R.array.cities);
		cityAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, cities);
		cityAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		citySpinner.setAdapter(cityAdapter);
		citySpinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int pos, long id) {
						arg0.setVisibility(View.VISIBLE);
						cityIndex = pos;
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});

		btn = (Button) this.findViewById(R.id.btn);

		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				curPage = 0;
				String keywords = ((EditText) findViewById(R.id.edit_input))
						.getText().toString();
				viewGone.setVisibility(View.GONE);
				viewLoading.setVisibility(View.VISIBLE);
				new LoadingItems().execute(keywords, cities[cityIndex]);

			}
		});
		viewMore.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!viewMore.getText().equals("更多"))
					return;

				String keywords = ((EditText) findViewById(R.id.edit_input))
						.getText().toString();
				new LoadingMoreItems().execute(keywords, cities[cityIndex]);
			}
		});
		orderBtn = (Button) findViewById(R.id.orderby);
		orderBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				curPage = 0;
				new AlertDialog.Builder(SearchActivity.this)
						// build AlertDialog
						.setTitle("选择排序方式")
						// title
						.setItems(R.array.order_method,
								new DialogInterface.OnClickListener() { // content
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										order = which;
										if (searchResultList.size() == 0)
											return;
										viewGone.setVisibility(View.GONE);
										viewLoading.setVisibility(View.VISIBLE);
										new LoadingItems()
												.execute(
														((EditText) findViewById(R.id.edit_input))
																.getText()
																.toString(),
														cities[cityIndex]);
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss(); // 关闭alertDialog
									}
								}).show();

			}
		});
	}

	/*
	 * generate request url
	 */
	public URL generateURL(String keywords, String location)
			throws JDOMException, IOException {
		String paras = "?";
		if (keywords != null) {
			String title = TextUtil.splitMultiKeywords(keywords);
			paras += "title=" + title + "&";
		}

		int page = ++curPage;
		int pageSize = Global.PAGINATION;

		paras += "page=" + page + "&pageSize=" + pageSize + "&cityName="
				+ URLEncoder.encode(cities[cityIndex]);
		String curOrder = "";
		switch (order) {
		case 0:
			curOrder += "&orderBy=endTime&order=asc";
			break;
		case 1:
			curOrder += "&orderBy=price&order=asc";
			break;
		case 2:
			curOrder += "&orderBy=discountPercent&order=asc";
			break;
		case 3:
			curOrder += "&orderBy=salesNum&order=desc";
			break;
		default:
			curOrder += "&orderBy=website";
		}
		paras += curOrder;
		Log.d("URL Request is ", paras);
		URL url = new URL(Global.SERVER_URL_BASE + paras);

		return url;
	}

	/*
	 * parse XML
	 */
	public void parseResult(URL url) throws JDOMException, IOException {
		searchResultList.clear();
		SAXBuilder builder = new SAXBuilder(false);
		Document doc = builder.build(url);

		Element root = doc.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> list = root.getChildren();
		int size = list.size();

		for (int i = 0; i < size; i++) {
			Element item = list.get(i);
			String title = item.getChildText("title");
			if (title.length() > 70) {
				title = title.substring(0, 70) + "...";
			}
			String price = item.getChildText("price");
			String dealValue = item.getChildText("dealValue");
			searchResultList.add(new ListItemResult(item.getChildText("oid"),
					item.getChildText("lImageUrl"), title, price.substring(0,
							price.indexOf(".")), dealValue.substring(0,
							dealValue.indexOf(".")), item
							.getChildText("discountPercent")));
		}

	}

	/*
	 * show in the list view
	 */
	public void showResults() {

		List<HashMap<String, Object>> mlist = new ArrayList<HashMap<String, Object>>();
		final Activity activity = this;

		int size = searchResultList.size();
		for (int i = 0; i < size; i++) {
			ListItemResult result = searchResultList.get(i);
			HashMap<String, Object> mMap = new HashMap<String, Object>();
			Log.i("null", "imageList ");
			mMap.put("image", images.get(i));
			// mMap.put("image", R.drawable.icon);
			mMap.put("title", result.getTitle());
			mMap.put("price", result.getPrice());
			mMap.put("dealValue", result.getDealValue());
			mMap.put("oid", result.getOid());
			mlist.add(mMap);
		}

		searchAdapter = new SearchAdapter(this, mlist, R.layout.list_item,
				new String[] { "image", "title", "price", "dealValue", "oid" },
				new int[] { R.id.image_deal, R.id.deal_title, R.id.deal_price,
						R.id.deal_dealValue, R.id.deal_oid });

		lv.setAdapter(searchAdapter);
		lv.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				lastVisibleItem = firstVisibleItem + visibleItemCount;
				if (lastVisibleItem > 0 && lastVisibleItem == totalItemCount) {
					viewMore.setVisibility(View.VISIBLE);
				} else
					viewMore.setVisibility(View.GONE);
				Log.i("last visible item count", lastVisibleItem + "");
			}

			@Override
			public void onScrollStateChanged(AbsListView view, int state) {

			}
		});
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
				String oid = ((TextView) v.findViewById(R.id.deal_oid))
						.getText().toString();
				Intent viewDetail = new Intent(activity, DetailActivity.class);
				viewDetail.putExtra("oid", oid);
				startActivity(viewDetail);
			}
		});
	}

	private void showMoreResults() {
		List<HashMap<String, Object>> mlist = new ArrayList<HashMap<String, Object>>();

		int size = searchResultList.size();
		if (size == 0)
			return;
		for (int i = 0; i < size; i++) {
			ListItemResult result = searchResultList.get(i);
			HashMap<String, Object> mMap = new HashMap<String, Object>();
			Log.i("null", "imageList ");
			mMap.put("image", images.get(i));
			// mMap.put("image", R.drawable.icon);
			mMap.put("title", result.getTitle());
			mMap.put("price", result.getPrice());
			mMap.put("dealValue", result.getDealValue());
			mMap.put("oid", result.getOid());
			mlist.add(mMap);
		}
		searchAdapter.appendData(mlist);
		searchAdapter.notifyDataSetChanged();
	}

	/*
	 * load images
	 */
	private void loadImages() {
		images.clear();
		int size = searchResultList.size();

		for (int i = 0; i < size; i++) {
			ListItemResult result = searchResultList.get(i);
			String imageUrl = result.getUrl();
			images.add(imageUrl);
		}
	}

	private class LoadingItems extends AsyncTask<String, Void, Void> {
		private boolean gone = false;
		private boolean moreItems = false;

		@Override
		protected void onPreExecute() {
			viewGone.setVisibility(View.GONE);
			viewLoading.setVisibility(View.VISIBLE);
			viewMore.setText("更多");
			viewMore.setVisibility(View.GONE);
			lv.setVisibility(View.GONE);
		}

		@Override
		protected Void doInBackground(String... arg0) {
			try {

				URL url = generateURL(arg0[0], arg0[1]);
				parseResult(url);
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (searchResultList.size() != 0) {
				gone = false;
				if (searchResultList.size() % Global.PAGINATION == 0) {
					moreItems = true;
				}
				loadImages();

			} else {
				moreItems = false;
				gone = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void unused) {
			viewLoading.setVisibility(View.GONE);

			if (gone) {
				lv.setVisibility(View.GONE);
				viewGone.setVisibility(View.VISIBLE);
			} else {
				viewGone.setVisibility(View.GONE);
				showResults();
				lv.setVisibility(View.VISIBLE);
				if (moreItems)
					viewMore.setVisibility(View.VISIBLE);
				else {
					viewMore.setText("没有更多了");
					viewMore.setVisibility(View.GONE);
				}
			}
		}

	}

	private class LoadingMoreItems extends AsyncTask<String, Void, Void> {
		private boolean moreItems = false;

		@Override
		protected void onPreExecute() {
			viewMore.setText("加载中...");
			viewMore.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(String... arg0) {
			try {

				URL url = generateURL(arg0[0], arg0[1]);
				parseResult(url);
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (searchResultList.size() != 0) {
				if (searchResultList.size() % Global.PAGINATION == 0) {
					moreItems = true;
				}
				loadImages();

			} else
				moreItems = false;

			return null;
		}

		@Override
		protected void onPostExecute(Void unused) {
			if (moreItems) {
				viewMore.setText("更多");
			} else {
				viewMore.setText("没有更多了");
			}
			showMoreResults();
		}
	}
}
